package logic

import (
	"context"
	"strconv"
	"strings"

	// "demo/internal/errorx"
	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	sq "github.com/Masterminds/squirrel"

	// "strconv"

	"github.com/zeromicro/go-zero/core/logx"
)


type ServeyInfoLogic struct{
	logx.Logger
	ctx context.Context
	svcCtx *svc.ServiceContext
	modelS model.ServeyModel
}

func NewServeyInfoLogic(ctx context.Context,svcCtx *svc.ServiceContext)*ServeyInfoLogic{
	return &ServeyInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx: ctx,
		svcCtx: svcCtx,
		modelS: model.NewServeyModel(svcCtx.Orm,svcCtx.Config.Cache),
	}
}

func (l *ServeyInfoLogic)Info(req *types.ServeyInfoRequest)(resp *types.ServeyInfoResponse,err error){
	// 直接查询 servey
	query := l.modelS.SelectBuilder()
	if len(strings.TrimSpace(req.Title)) > 0{
		query = query.Where(sq.ILike{"title": "%"+ req.Title +"%"})
	}
	if req.Id != 0 {
		query = query.Where(sq.Eq{"id": req.Id})
	}
	if req.IsPublic != nil {
		query = query.Where(sq.Eq{"is_public": req.IsPublic})
	}
	if req.IsEnd != nil {
		query = query.Where(sq.Eq{"is_end": req.IsEnd})
	}
	query.Where(sq.Eq{"is_deleted":no_delete})
	start := (req.Page - 1) * req.PageSize
	query = query.Limit(uint64(req.PageSize)).Offset(uint64(start))
	sqlData,err := l.modelS.GetListByPage(l.ctx,nil,query)
	if err != nil {
		return nil,errorx.NewBizError(500,err.Error())
	}
	data := make([]types.ServeyItemResponse,0)
	for _,val := range sqlData {
		item := &types.ServeyItemResponse{
			Id: val.Id,
			CreatorId: val.CreatorId,
			Title: val.Title,
			Description: val.Description,
			CreateTime: strconv.FormatInt(val.CreateTime,10),
			PublishTime: strconv.FormatInt(val.PublishTime,10),
			EndTime: strconv.FormatInt(val.EndTime,10),
			IsPublic: val.IsPublic,
			IsEnd: val.IsEnd,
			VisitNum: val.VisitNum,
		}
		data = append(data, *item)
	}
	
	return &types.ServeyInfoResponse{
		Code: 200,
		Msg: "查询成功",
		Data: data,
	},nil
}